package com.hulk.rpc.discover;

import com.hulk.rpc.config.common.HostPort;
import com.hulk.rpc.discover.local.DirectDiscover;
import com.hulk.rpc.discover.zk.ZooKeeperDiscover;
import com.hulk.rpc.exception.HulkRpcException;
import com.hulk.rpc.config.server.ProtocolType;

import java.io.Closeable;
import java.util.List;

/**
 * @author xuxukang
 * @date 2019-04-15 17:12
 */
public interface Discover extends Closeable {

  /**
   * 初始注册中心客户端连接，或保存直连app资源
   *
   * @param hostPorts 注册中心地址或app地址列表
   */
  void init(List<HostPort> hostPorts);

  /**
   * 开始监听注册中心相关事件
   */
  void startRegistryListener(String group, String app, ProtocolType protocolType,
                             DiscoverListener listener);

  enum DiscoverEnum {
    /**
     * 发现器工厂
     */
    direct(DirectDiscover.class),
    zookeeper(ZooKeeperDiscover.class);

    private Class<? extends Discover> discoverClass;

    DiscoverEnum(Class<? extends Discover> discoverClass) {
      this.discoverClass = discoverClass;
    }

    public Discover getDiscover() {
      try {
        return discoverClass.getDeclaredConstructor().newInstance();
      } catch (Exception e) {
        throw new HulkRpcException(e);
      }
    }

    public static DiscoverEnum match(String name, DiscoverEnum defaultDiscover) {
      for (DiscoverEnum item : DiscoverEnum.values()) {
        if (item.name().equals(name)) {
          return item;
        }
      }
      return defaultDiscover;
    }
  }

}
